import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.core.CvType;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

import static org.opencv.core.Core.convertScaleAbs;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-04-09
 * Time: 19:31
 */
public class Test {
    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    /**
     * 用于整体偏暗图像的增强,变亮
     */
    public static Mat laplaceEnhance(Mat src) {
        Mat srcClone = src.clone();
//        float[] kernel = {0, 0, 0, -1, 5f, -1, 0, 0, 0};
        float[] kernel = {0, 0, 0, -1, 5f, -1, 0, 0, 0};
        Mat kernelMat = new Mat(3, 3, CvType.CV_32FC1);
        kernelMat.put(0, 0, kernel);
        Imgproc.filter2D(srcClone, srcClone, CvType.CV_8UC3, kernelMat);
        return srcClone;
    }

    /**
     * 锐化
     * @param src
     * @return
     */
    public static Mat sharpen(Mat src) {
        Mat tmp = new Mat();
        Mat dst = new Mat();
        Imgproc.GaussianBlur(src, tmp, new Size(0, 0), 100, 100);
        Core.addWeighted(src, 1.5, tmp, -0.5, 0, dst);
        return dst;
    }

    public static Mat white(Mat src) {
        //RGB三通道分离
        List<Mat> splitMat = new ArrayList<Mat>();
        Core.split(src, splitMat);
//得到RGB三个通道的均值
        double meanB = Core.mean(splitMat.get(0)).val[0];
        double meanG = Core.mean(splitMat.get(1)).val[0];
        double meanR = Core.mean(splitMat.get(2)).val[0];

//调整RGB三个通道的增益
        double kB = (meanB + meanG + meanR) / (3 * meanB);
        double kG = (meanB + meanG + meanR) / (3 * meanG);
        double kR = (meanB + meanG + meanR) / (3 * meanR);

//调整RGB三个通道的值
        List<Mat> mergeMatList = new ArrayList<>();
        Mat merge = new Mat();
        Mat newMat = new Mat(splitMat.get(0).size(), CvType.CV_8UC1);
        Mat newMat1 = new Mat(splitMat.get(1).size(), CvType.CV_8UC1);
        Mat newMat2 = new Mat(splitMat.get(2).size(), CvType.CV_8UC1);
        convertScaleAbs(splitMat.get(0),newMat,kB);
        convertScaleAbs(splitMat.get(1),newMat1,kG);
        convertScaleAbs(splitMat.get(2),newMat2,kR);
        mergeMatList.add(newMat);
        mergeMatList.add(newMat1);
        mergeMatList.add(newMat2);

//合并三通道
        Core.merge(mergeMatList, merge);
        return merge;
    }

    public static void main(String[] args) {
        Mat src = Imgcodecs.imread("03.tif");
        HighGui.imshow("src",src);
        HighGui.waitKey(0);

        //Mat mat = laplaceEnhance(src);
        //Mat mat3 = white(mat);

        Mat mat3 = white(src);

        Mat mat1 = sharpen(mat3);
        Mat mat2 = sharpen(mat1);
        HighGui.imshow("mat1",mat2);
        HighGui.waitKey(0);
    }
}
